package com.zftlive.springbooot.main;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 应用程序启动类
 *
 * @author zengfantian
 * @version 1.0
 */
@RestController
@ComponentScan(value = "com.zftlive")
@SpringBootApplication
@Slf4j
public class MainApplication {


    @Value("${application.deploy.buildTime}")
    private String buildTime;

    @Value("${spring.application.name}")
    private String appName;

    /**
     * 启动时间
     */
    private static LocalDateTime onlineTime = LocalDateTime.now();

    /**
     * 获取服务名称以及启动时间信息
     *
     * @return
     */
    @RequestMapping("/")
    public String getServerInfo() {
        return new StringBuilder()
                .append("系统名称：").append(appName).append("\n")
                .append("打包时间：").append(buildTime).append("\n")
                .append("启动时间：").append(onlineTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).toString();
    }

    /**
     * 获取服务版本信息
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("/package")
    public Object getPackageInfo() throws IOException {
        File packageJson = new File("../package.json");
        if (!packageJson.exists()) {
            String rootDir = System.getProperty("user.dir");
            packageJson = new File(rootDir, "package.json");
        }

        if (!packageJson.exists()) {
            return "未查找到package.json文件信息";
        }

        try{
            InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(packageJson), StandardCharsets.UTF_8);
            Reader reader = new BufferedReader(inputStreamReader);
            Map versionInfo = new Gson().fromJson(reader, HashMap.class);
            return versionInfo;
        }catch (Throwable e){
            log.error("获取package.json数据失败，原因："+e.getMessage(),e);
        }

        return "";
    }

    /**
     * 应用启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }

}
